
package cn.zlg.common.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectionUtils {

    public static boolean isEmpty(Collection c) {
        return c == null || c.isEmpty();
    }

    public static boolean isNotEmpty(Collection c) {
        return c != null && !c.isEmpty();
    }

    public static <R, T> List<T> extractProperty(Collection<R> c, Function<R, T> method) {
        return c.stream().map(method).collect(Collectors.toList());
    }

    public static <R, T> List<T> extractPropertyNotNull(Collection<R> c, Function<R, T> method) {
        return c.stream().map(method).filter(Objects::nonNull).collect(Collectors.toList());
    }

    public static <R, T> Map<T, R> toMap(Collection<R> c, Function<R, T> keyMethod) {
        Map<T, R> map = new HashMap<T, R>();
        c.forEach(r -> {
            map.put(keyMethod.apply(r), r);
        });
        return map;
    }

    /**
     * 调用 splitAndConvert(str, seperator, method, true, false)
     * 
     * @param <T>
     *            需要转换的目标类型
     * @param str
     *            需转换的字符串
     * @param seperator
     *            分隔符
     * @param method
     *            转换函数
     * @return 转换结果
     */
    public static <T> List<T> splitAndConvert(String str, String seperator, Function<String, T> method) {
        return splitAndConvert(str, seperator, method, true, false);
    }

    /**
     * 拆分字符串，并转换成List
     * 
     * @param <T>
     *            目标类型
     * @param str
     *            需转换的字符串
     * @param seperator
     *            分隔符
     * @param method
     *            转换函数
     * @param blankStrAsNull
     *            是否将空白字符转换为null。true:是，false:否
     * @param keepNull
     *            是否将null包含到结果List中。true:是，false:否
     * @return 转换结果
     */
    public static <T> List<T> splitAndConvert(String str, String seperator, Function<String, T> method,
            boolean blankStrAsNull, boolean keepNull) {
        String[] ss = str.split(seperator);
        List<T> list = new ArrayList<T>(ss.length);
        for (String s : ss) {
            if (s == null || s.trim().length() == 0) {
                // 空白字符串
                if (blankStrAsNull) {
                    if (keepNull) {
                        list.add(null);
                    }
                } else {
                    T apply = method.apply(s);
                    if (apply != null || keepNull) {
                        list.add(apply);
                    }
                }
            } else {
                T apply = method.apply(s);
                if (apply != null || keepNull) {
                    list.add(apply);
                }
            }
        }
        return list;
    }

}
